package com.marry.file.util;

import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @path：com.marry.file.util.RedisUtil.java
 * @className：RedisUtil.java
 * @description：Redis工具类
 * @author：LiuYun
 * @dateTime：2021/7/22 1:23
 * @editNote：
 */
public class RedisUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    //写入对象
    public boolean setObject(final String key, Object value, Integer expireTime) {
        try {

            redisTemplate.opsForValue().set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取对象
     *
     * @param key
     * @return
     */
    public Object getObject(final String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }


    /**
     * 写入集合
     *
     * @param key
     * @param value
     * @param expireTime
     * @return
     */
    public boolean setList(final String key, Object value, Integer expireTime) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取集合
     *
     * @param key
     * @return
     */
    public List<Object> getList(final String key) {
        try {
            return redisTemplate.opsForList().range(key, 0, -1);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 判断时候存在key
     *
     * @param key
     * @return
     */
    public boolean hasKey(final String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除key
     *
     * @param key
     */
    public void del(final String key) {
        if (hasKey(key)) {
            redisTemplate.delete(key);
        }
    }
}
